import datetime
import time
from nonebot.adapters.cqhttp import Bot as CQHTTPBot
from nonebot.adapters.cqhttp.event import Event
from nonebot.adapters.cqhttp.permission import _group_member

from nonebot.plugin import on_command
from nonebot.rule import to_me
from nonebot.typing import T_State
from pydantic.utils import truncate

from ...dao import assignment_dao, user_dao, submit_record_dao

from ..teacher.launch_attendance import GroupAttendDict
from ...dao.db_context import DBConnection

attend = on_command("签到", rule=to_me())

@attend.handle()
async def attend_handler(bot: CQHTTPBot, event: Event, state: T_State):
    current_time = int(round((time.time()) * 1000))
    #check if the student(qqid) is bound with studentID
    user_id = event.get_user_id()
    studentID = await user_dao.get_stuID(user_id)
    if studentID is None:
        await attend.finish(message="请先使用'/绑定'绑定自己的学号，然后再使用'/签到'")
    
    attending_groupid = None
    #find the attending_group, if any
    for key, value in GroupAttendDict().attend.items():
        if current_time - value < 1000 * 60 * 10:
            attending_groupid = key
            break
    
    #handle no attending_group case
    if attending_groupid is None:
        await attend.finish(message="当前不在签到时间")
    
    #check if the student is in the group
    group_member_list = await bot.get_group_member_list(group_id=attending_groupid)
    group_user_id_list = []
    for group_member in group_member_list:
        group_user_id_list.append(group_member["user_id"])
    not_in = True
    for id in group_user_id_list:
        if int(user_id) == int(id):
            not_in = False
            break
    if not_in:
        await attend.finish(message="当前不在签到时间")
    
    #insert the submit into DB if everything is right
    attendance_id = await assignment_dao.get_assignment_id(attending_groupid, str(datetime.date.today()))
    
    await submit_record_dao.modify_record(attendance_id[0], studentID[0])
    
    await bot.send(message="签到成功！", event=event)    
        
    
    
